#!/bin/sh
CONF=/etc/config/qpkg.conf
QPKG_NAME="Redis"
# QPKG_INSTALL_PATH=`/sbin/getcfg $QPKG_NAME Install_Path -f ${CONF}`
QPKG_INSTALL_PATH=$(/sbin/getcfg $QPKG_NAME Install_Path -d UNKNOWN -f $CONF)

# QPKG_WEBUI=$(/sbin/getcfg $QPKG_NAME WebUI -d UNKNOWN -f $CONF)
# [ -d /share/Web ] && SYS_WEB_SHARE="/share/Web"
# [ -d /share/Qweb ] && SYS_WEB_SHARE="/share/Qweb"

CMD_LN="/bin/ln"
CMD_RM="/bin/rm"
QPKG_LOG_PATH=${QPKG_INSTALL_PATH}/log

[ -d "$QPKG_LOG_PATH" ] || mkdir $QPKG_LOG_PATH

QPKG_LOG=${QPKG_LOG_PATH}/redis-sh.log

#include logger
. ${QPKG_INSTALL_PATH}/logger.sh
scriptname=`basename "$0"`
exec >> ${QPKG_LOG} 2>&1

logEnterScript $scriptname $LINENO

pid_file=$QPKG_INSTALL_PATH/redis.pid

function start() {
	echo "启动redis"
    logEnterFunction "start" $scriptname $LINENO

    ENABLED=$(/sbin/getcfg $QPKG_NAME Enable -u -d FALSE -f $CONF)
    if [ "$ENABLED" != "TRUE" ]; then
        echo "$QPKG_NAME is disabled."
        logError "$QPKG_NAME is disabled." $scriptname $LINENO
        exit 1
    fi
    
    #create web symbolic link
    #${CMD_LN} -sfn ${QPKG_INSTALL_PATH}/web ${SYS_WEB_SHARE}/${QPKG_WEBUI}
    # ${CMD_LN} -sfn ${QPKG_INSTALL_PATH}/web ${SYS_WEB_SHARE}/${QPKG_NAME}
    RETVAL=$?
    logDebug "create web symbolic link retval=$RETVAL" $scriptname $LINENO

    # 给start.sh加上可执行属性
    chmod +x $QPKG_INSTALL_PATH/bin/redis-server

    echo "$QPKG_NAME is enabled."
	
	# sh $QPKG_INSTALL_PATH/bin/start.sh
	
	$QPKG_INSTALL_PATH/bin/redis-server /etc/config/redis.conf > /dev/null 2>&1 & 
	# pgrep -P $! >  ${pid_file}
	ps -e -o pid,cmd | awk '/redis-server/ && !/awk/'|awk '{print $1}' >  ${pid_file}

	# $? 获取上一条命令的退出状态
	# $!：Shell最后运行的后台Process的PID(后台运行的最后一个进程的 进程ID号)
	# if [[ $? -eq 0 ]]; then
       # echo $1 > ${pid_file}
    # else 
       # exit 1
    # fi

    logDebug "启动redis结束，进程写入pid文件" $scriptname $LINENO
	
	logExitFunction "start" $scriptname $LINENO
}

function stop(){
	echo "停止redis"
    logExitFunction "stop" $scriptname $LINENO
    
    #remove web symbolic link
    # ${CMD_RM} -f ${SYS_WEB_SHARE}/${QPKG_NAME}

    #remove web symbolic link
    #${CMD_RM} -f ${SYS_WEB_SHARE}/${QPKG_WEBUI}
    
    chmod -x $QPKG_INSTALL_PATH/bin/redis-server

    RETVAL=$?
    logDebug "remove web symbolic link retval=$RETVAL" $scriptname $LINENO

    logExitFunction "stop" $scriptname $LINENO
	
	kill -9 $(cat ${pid_file})
    # shellcheck disable=SC2181
    if [[ $? -eq 0 ]]; then
        rm -f ${pid_file}
    else exit 1
    fi
}

case "$1" in
  start)
	start
    ;;

  stop)
    : ADD STOP ACTIONS HERE
	stop;
    ;;

  restart)
    logEnterFunction "restart" $scriptname $LINENO
    $0 stop
    $0 start
    logExitFunction "restart" $scriptname $LINENO
    ;;

  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
